{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "provenance": [],
      "gpuType": "T4"
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    },
    "accelerator": "GPU",
    "gpuClass": "standard"
  },
  "cells": [
    {
      "cell_type": "markdown",
      "source": [
        "Copyright 2023 Google LLC\n",
        "\n",
        "Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "you may not use this file except in compliance with the License.\n",
        "You may obtain a copy of the License at\n",
        "\n",
        "  https://www.apache.org/licenses/LICENSE-2.0\n",
        "\n",
        "Unless required by applicable law or agreed to in writing, software\n",
        "distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "See the License for the specific language governing permissions and\n",
        "limitations under the License."
      ],
      "metadata": {
        "id": "AgIWLkwN4kTE"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Proto-Value Networks\n",
        "\n",
        "This colab contains sample code to load and perform inference on the PVN models included in the paper."
      ],
      "metadata": {
        "id": "NTqNwf6mMQJ_"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# @title Imports\n",
        "import tensorflow as tf\n",
        "import numpy as np\n",
        "\n",
        "assert tf.test.gpu_device_name(), \"No GPU found, change the device runtime.\""
      ],
      "metadata": {
        "cellView": "form",
        "id": "zUmbfS__SUXE"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# @title Download PVN model\n",
        "import os\n",
        "import pathlib\n",
        "import subprocess\n",
        "\n",
        "\n",
        "game = \"Freeway\"  # @param ['AirRaid', 'Alien', 'Amidar', 'Assault', 'Asterix', 'Asteroids', 'Atlantis', 'BankHeist', 'BattleZone', 'BeamRider', 'Berzerk', 'Bowling', 'Boxing', 'Breakout', 'Carnival', 'Centipede', 'ChopperCommand', 'CrazyClimber', 'DemonAttack', 'DoubleDunk', 'ElevatorAction', 'Enduro', 'FishingDerby', 'Freeway', 'Frostbite', 'Gopher', 'Gravitar', 'Hero', 'IceHockey', 'Jamesbond', 'JourneyEscape', 'Kangaroo', 'Krull', 'KungFuMaster', 'MontezumaRevenge', 'MsPacman', 'NameThisGame', 'Phoenix', 'Pitfall', 'Pong', 'Pooyan', 'PrivateEye', 'Qbert', 'Riverraid', 'RoadRunner', 'Robotank', 'Seaquest', 'Skiing', 'Solaris', 'SpaceInvaders', 'StarGunner', 'Tennis', 'TimePilot', 'Tutankham', 'UpNDown', 'Venture', 'VideoPinball', 'WizardOfWor', 'YarsRevenge', 'Zaxxon']\n",
        "# @markdown The name of the game in \"Gym\" (aka camel case) format.\n",
        "# @markdown e.g., Freeway, Breakout, SpaceInvaders.\n",
        "run = 1 # @param [1, 2, 3]\n",
        "# @markdown Runs are 1-3 inclusively and correspond\n",
        "# @markdown to the RLDS seed used for data collection.\n",
        "\n",
        "# Create game directory\n",
        "gamedir = pathlib.Path('/content') / game\n",
        "gamedir.mkdir(parents=True, exist_ok=True)\n",
        "\n",
        "command = [\n",
        "    \"gsutil\",\n",
        "    \"-q\",\n",
        "    \"-m\",\n",
        "    \"cp\",\n",
        "    \"-R\",\n",
        "    f\"gs://download-dopamine-rl/pvn/{game}/{run}/*\",\n",
        "    gamedir.as_posix(),\n",
        "]\n",
        "\n",
        "print(f\"$ {' '.join(command)}\", flush=True)\n",
        "process = subprocess.Popen(\n",
        "    command,\n",
        "    stdout=subprocess.PIPE,\n",
        "    stderr=subprocess.STDOUT,\n",
        "    text=True,\n",
        ")\n",
        "\n",
        "for line in process.stdout:\n",
        "  print(line.rstrip(), flush=True)\n",
        "\n",
        "assert process.wait() == 0, \"Process finished with non-zero error code\"\n",
        "print(f\"Finished downloading {game} PVN model.\")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "Xw6m9jvtMSep",
        "outputId": "f378830c-bc56-412b-97d3-d6bc536db970",
        "cellView": "form"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "$ gsutil -q -m cp -R gs://download-dopamine-rl/pvn/Freeway/1/* /content/Freeway\n",
            "Finished downloading Freeway PVN model.\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# @title Reload saved model\n",
        "with tf.device('/device:GPU:0'):\n",
        "  pvn = tf.saved_model.load(gamedir.as_posix())"
      ],
      "metadata": {
        "id": "NbWbk40xlgzl",
        "cellView": "form"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# @title Perform forward pass to get PVN features\n",
        "# Atari observation: [batch_size, width, height, frame_stack]\n",
        "obs = np.zeros((1, 84, 84, 4))\n",
        "\n",
        "with tf.device('/device:GPU:0'):\n",
        "  features = pvn(obs).numpy()\n",
        "  print(f\"Shape: {features.shape!r}\")\n",
        "  print(features)"
      ],
      "metadata": {
        "id": "GO89UUxzmP2V",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "cellView": "form",
        "outputId": "02e16dd7-d621-4cc0-be7d-720ab7cd9e30"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Shape: (1, 4096)\n",
            "[[0.02910921 0.00624304 0.00605449 ... 0.142218   0.         0.        ]]\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [],
      "metadata": {
        "id": "CTV2i_C2q05Z"
      },
      "execution_count": null,
      "outputs": []
    }
  ]
}